//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect } from "react";
import stores, { useRoadmapStores } from './store/index';
import { BrowserRouter, useLocation } from "react-router-dom";
import { Provider } from 'mobx-react';
import { ConfigProvider, message } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import { createRoot } from 'react-dom/client';
import 'remirror/styles/all.css';
import '@/components/Editor/editor.less';
import '@/styles/global.less';
import 'reactflow/dist/base.css';
import RoadmapBoard from "./RoadmapBoard";
import { report_error } from "@/api/client_cfg";

const RoadmapApp = () => {
    const roadmapStore = useRoadmapStores();

    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const roadmapId = urlParams.get("roadmapId") ?? "";
    const sessionId = urlParams.get("sessionId") ?? "";
    const adminUserStr = (urlParams.get("adminUser") ?? "").toLowerCase();
    const canUpdateStr = (urlParams.get("canUpdate") ?? "").toLowerCase();
    const nodeId = urlParams.get("nodeId") ?? "";
    const showNoteStr = (urlParams.get("showNote") ?? "").toLowerCase();

    const init = async () => {
        roadmapStore.init(roadmapId, sessionId, adminUserStr.startsWith("t"), canUpdateStr.startsWith("t"), showNoteStr.startsWith("t"));
        await roadmapStore.loadRoadmapInfo();
        await roadmapStore.loadNodeList();
        await roadmapStore.loadEdgeList();
        await roadmapStore.loadStateList();
        await roadmapStore.loadNoteList();
        if (nodeId != "" && adminUserStr.startsWith("f")) {
            roadmapStore.selectNodeId = nodeId;
        }
    };

    useEffect(() => {
        init();
    }, [roadmapId, sessionId, adminUserStr, canUpdateStr, nodeId]);

    return (
        <RoadmapBoard />
    );
};

const App = () => {
    return (
        <Provider {...stores}>
            <ConfigProvider locale={zhCN}>
                <BrowserRouter>
                    <RoadmapApp />
                </BrowserRouter>
            </ConfigProvider>
        </Provider>
    );
}

const root = createRoot(document.getElementById('root')!);
root.render(<App />);

window.addEventListener('unhandledrejection', function (event) {
    // 防止默认处理（例如将错误输出到控制台）
    event.preventDefault();
    if (`${event.reason}`.includes("error trying to connect")) {
      return;
    }
    message.error(event?.reason);
    // console.log(event);
    try {
      report_error({
        err_data: `${event?.reason}`,
      });
    } catch (e) {
      console.log(e);
    }
  });